<?php
class common_media_image {
	
	public static function create($src) {
		if(empty($src)) {
			throw new common_exception("Image is empty.");
		}
		$content = file_get_contents($src['tmp_name']);
		if(!$content) {
			throw new common_exception("Image is empty.");
		}
		$type = self::getType(null, $content);
		$filter = common_media_config::$imageFilter;
		if(empty($type) || !in_array($type, $filter)) {
			throw new common_exception("Image type is not suppoted,it should be a(n) '" . implode(',', $filter) . "' file.");
		}
		$md5 = system_file_io::md5Filename(null, $content);
		$md5code = common_media_config::md5Path($md5);
		$md5file = common_media_config::imagePath() . $md5code;
		$md5name = '/original.' . $type;
		if(!file_exists($md5file . $md5name)) {
			system_file_io::mkdir($md5file);
			if(!file_put_contents($md5file . $md5name, $content)) {
				throw new common_exception("Save file faild,Please check if the folder is writable.");
			}
			$thumb = system_image_factory::create($md5file . $md5name);
			foreach(common_media_config::$sizes as $key => $name) {
				$thumb->loadImage()->resize($key)->save($md5file . '/' . $name . '.' . $type);
			}
		}
		$tConcept = new common_media_type('image'); // 图片
		$content = new common_media_concept();
		if(!($row = $content->fetch(array('md5 = ?' => $md5code)))) {
			$row = $content->create();
			$row->setMd5($md5);
			$row->setHtype($tConcept->getId());
			$row->setSize($src['size']);
			$row->setExtension($type);
			$row->setType($src['type']);
		}
		return $row;
	}
	
	private static function getType($filename = null, $content = null) {
		if($filename && !$content) {
			$header = file_get_contents($filename, 0, NULL, 0, 5);
		} else {
			$header = substr($content, 0, 5);
		}
		if($header{0} . $header{1} == "\x89\x50") {
			return 'png';
		} else {
			if($header{0} . $header{1} == "\xff\xd8") {
				return 'jpg';
			} else {
				if($header{0} . $header{1} . $header{2} == "\x47\x49\x46") {
					if($header{4} == "\x37") {
						return 'gif87';
					} else {
						if($header{4} == "\x39") return 'gif89';
					}
				}
			}
		}
		$filetype = trim(system_file_io::getFileType($filename));
		return $filetype ? $filetype : 'unknown';
	}

}